MAGENTO 2 HOW TO CREATE CUSTOM QUERY

Magento 2 How to create custom query that is the question sometime is popped up on your head. Here is how I create my own custom queries in Magento 2.
Currently, I figured out two ways :

1/ Take advantage of using Magento Resource Connection.

$themeId=3;

$this->_resources = MagentoFrameworkAppObjectManager::getInstance()
->get(‘MagentoFrameworkAppResourceConnection’);
$connection= $this->_resources->getConnection();

$select = $connection->select()
->from(
[‘o’ => $this->_resources->getTableName(‘theme’)]
)->where(‘o.theme_id=?’,$themeId);

$result = $connection->fetchAll ($select);
var_dump($result);

You can change the query to insert, update or delete according to zend framework. It’s just an example code, you should put $connection in a  property of a helper class and use it from this help class.

2/The other way is reusing Magento Object Manager to create a collection:
$objectManager = MagentoFrameworkAppObjectManager::getInstance();

$productCollection = $objectManager->create(‘MagentoCatalogModelResourceModelProductCollectionFactory’);//insert your custom resource model

$collection = $productCollection->create()
->addAttributeToSelect(‘*’)
->load();

foreach ($collection as $product){
echo ‘Name = ‘.$product->getName().'<br>’;
}

$objectManager = MagentoFrameworkAppObjectManager::getInstance();

$productCollection = $objectManager->create(‘MagentoCatalogModelResourceModelProductCollectionFactory’);//insert your custom resource model

$collection = $productCollection->create()
->addAttributeToSelect(‘*’)
->load();

foreach ($collection as $product){
echo ‘Name = ‘.$product->getName().'<br>’;
}

 

 

 

 

 

Leave a Comment